package com.example.goods_manage.service.impl;

import com.example.goods_manage.dto.User;
import com.example.goods_manage.mapper.UserMapper;
import com.example.goods_manage.service.UserService;
import com.example.goods_manage.utils.AjaxResult;
import com.example.goods_manage.utils.JWTUtil;
import com.example.goods_manage.utils.cache.GuavaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@SuppressWarnings({"unchecked", ""})
@Service
public class UserServiceImpl implements UserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    private UserMapper userMapper;


    //验证码缓存工具类
    @Autowired
    private GuavaMap<String,String> codeGuavaMap;


    @Override
    public AjaxResult login(User user) {

        //从缓存中获取验证码：与前端传来的 code 进行校验
        String codeVal = codeGuavaMap.get(user.getCodeKey());
        if(!user.getCodeVal().equals(codeVal)){
            //这里可以返回不同的code 让前端进行识别，然后让其重新调用获取验证码的接口
            //这里没有判断前端的code 是否为空，如果没有传 会抛出异常
            return AjaxResult.error("验证码错误,请重新刷新验证码");
        }

        User account = userMapper.findUserByAccount(user);


        if (account == null) {
            return AjaxResult.error("用户不存在");
        }

        if (!account.getPassword().equals(user.getPassword())) {
            return AjaxResult.error("用户名或密码错误");
        }

        //生成token 返回给前端
        String token = JWTUtil.generateToken(account.getId());
        account.setToken(token);



        return AjaxResult.success(account);
    }

    /**
     * 注册用户
     * 1.判断用户是否存在
     * 2.不存在则插入用户数据到数据
     */
    @Override
    public AjaxResult register(User user) {
        User account = userMapper.findUserByAccount(user);
        if(ObjectUtils.isEmpty(account)){
            return AjaxResult.error("当前用户存在");
        }
        Integer result = userMapper.insertUser(user);
        if(result > 0){
            return AjaxResult.success("新增用户成功");
        }else {
            return AjaxResult.success("新增用户失败");
        }
    }
}
